CROSS_COMPILE	?= arm-linux-gnueabihf-
TARGET 		:= epit

CC			:= 	$(CROSS_COMPILE)gcc
LD			:= 	$(CROSS_COMPILE)ld
OBJCOPY		:= 	$(CROSS_COMPILE)objcopy
OBJDUMP		:= 	$(CROSS_COMPILE)objdump


INCLUDEDIRS :=  bsp/clk \
				bsp/delay \
				bsp/led \
				imx6ull \
				bsp/beep \
				bsp/gpio \
				bsp/key \
				bsp/int \
				bsp/exti \
				bsp/epittimer

SRCDIRS		:=	bsp/clk \
				bsp/delay \
				bsp/led \
				project \
				bsp/beep \
				bsp/gpio \
				bsp/key \
				bsp/int \
				bsp/exti \
				bsp/epittimer

INCLUDE		:= 	$(patsubst %, -I %, $(INCLUDEDIRS))


#SFILES		:=	$(patsubst %.s,%.s,$(wildcard $(SRCDIRS)/*.s))
#CFILES		:=	$(patsubst %.c,%.c,$(wildcard $(SRCDIRS)/*.c)) 
#SFILES		:=	$(wildcard $(SRCDIRS)/*.s)
#CFILES		:=	$(wildcard $(SRCDIRS)/*.c)

#错误的语法格式，因为 $(wildcard $(SRCDIRS)/*.c) 展开之后为 "$(wildcard bsp/clk bsp/delay bsp/led project/*.c)",这样只有最后一个展开为了 $(wildcard project/*.c)的形式
#按照我们的预期，应该使用 Makefile 的 $(foreach var,list,text) 函数
##

SFILES		:= 	$(foreach dir, $(SRCDIRS), $(wildcard $(dir)/*.S))
CFILES		:= 	$(foreach dir, $(SRCDIRS), $(wildcard $(dir)/*.c))

SFILENDIR	:= 	$(notdir $(SFILES))
CFILENDIR	:= 	$(notdir $(CFILES))

SOBJS		:=	$(patsubst %, obj/% ,$(SFILENDIR:%.S=%.o))
COBJS		:=	$(patsubst %, obj/%, $(CFILENDIR:%.c=%.o))


OBJS		:=	$(SOBJS) $(COBJS)

VPATH		:= 	$(SRCDIRS)


$(TARGET).bin : $(OBJS)
	echo $(LD) $(TARGET).elf
	$(LD) -Timx6u.lds -o $(TARGET).elf $^
	$(OBJCOPY) -O binary -S $(TARGET).elf $(TARGET).bin
	$(OBJDUMP) -D -m arm $(TARGET).elf > $(TARGET).dis
#	$(OBJDUMP) -d -s -m arm $(TARGET).elf > $(TARGET).dis

# #%.o : %.s
$(SOBJS) : obj/%.o : %.S
	$(CC) -Wall -nostdlib $(INCLUDE) -O2 -c -o $@ $<
#	$(CC) -Wall -nostdlib $(INCLUDE) -c -o $@ $<

#%.o : %.c
$(COBJS) : obj/%.o : %.c
	$(CC) -Wall -nostdlib $(INCLUDE) -O2 -c -o $@ $<
#	$(CC) -Wall -nostdlib $(INCLUDE) -c -o $@ $<

clean:
	rm -rf obj/*.o $(TARGET).bin $(TARGET).elf $(TARGET).dis
	rm -rf load.imx

.PHONY : print clean 

print:
	@echo "INCLUDE=" $(INCLUDE)
	@echo "SFILES="  $(SFILES)
	@echo "CFILES="  $(CFILES)
	@echo "SFILENDIR=" $(SFILENDIR)
	@echo "CFILENDIR=" $(CFILENDIR)
	@echo "SOBJS="   $(SOBJS)
	@echo "COBJS="   $(COBJS)
	@echo "OBJS="    $(OBJS)
